﻿using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Pool;

public class PoolTool : SingletonMono<PoolTool>
{
    // 用于存储不同类型的对象池
    private Dictionary<string, ObjectPool<GameObject>> pools = new Dictionary<string, ObjectPool<GameObject>>();


    protected override void Awake()
    {
        base.Awake();
        PreFillPool(nameof(Card), 10, "Prefab/卡面");
        PreFillPool("ResourcesPoint", 30, "Prefab/资源点");
        PreFillPool(nameof(Chess), 20, "Prefab/棋子");
    }
    
    public void PreFillPool(string poolName, int count, string address)
    {

        ResourceRequest request = Resources.LoadAsync<GameObject>(address);

        request.completed += (asyncOperation) =>
        {
            // 加载完成后的处理
            if (request.asset != null)
            {
                GameObject prefab = request.asset as GameObject;
                if (!pools.ContainsKey(poolName))
                {
                    pools.Add(poolName, CreatePool(prefab));
                }

                var pool = pools[poolName];
                var preFillArray = new GameObject[count];
                for (int i = 0; i < count; i++)
                {
                    preFillArray[i] = pool.Get();
                }

                foreach (var obj in preFillArray)
                {
                    pool.Release(obj);
                }
            }
            else
            {
                Debug.LogError("资源加载失败");
            }
        };
       
    }

    // 创建对象池
    private ObjectPool<GameObject> CreatePool(GameObject prefab)
    {
        return new ObjectPool<GameObject>(
            createFunc: () => Instantiate(prefab, transform),
            actionOnGet: (obj) => obj.SetActive(true),
            actionOnRelease: (obj) => obj.SetActive(false),
            actionOnDestroy: Destroy,
            collectionCheck: false,
            defaultCapacity: 10,
            maxSize: 20
        );
    }

    // 从对象池中获取对象
    public GameObject GetObjectFromPool(string poolName)
    {
        if (pools.ContainsKey(poolName))
        {
                return pools[poolName].Get();
        }
        else
        {
            Debug.LogError($"Pool with name '{poolName}' does not exist.");
            return null;
        }
    }

    // 将对象释放回对象池
    public void ReleaseObjectToPool(string poolName, GameObject obj)
    {
        if (pools.ContainsKey(poolName))
        {
            obj.transform.SetParent(this.transform);
            obj.transform.position = Vector3.zero;
            obj.transform.rotation = Quaternion.identity;
            obj.transform.localScale = Vector3.one;
            pools[poolName].Release(obj);
        }
        else
        {
            Debug.LogError($"Pool with name '{poolName}' does not exist.");
        }
    }

    private void OnDisable()
    {
        foreach (var pair in pools)
        {
            pair.Value.Clear();
        }
    }
}
